package com.dashuaibran.joker.factory;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeanFactory {

	private static Properties propsProperties;

	private static Map<String, Object> propsMap;

	static {
		try {
			// 实例化对象
			propsProperties = new Properties();
			// 获取流对象
			InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
			propsProperties.load(inputStream);
			// 实例化map
			propsMap = new HashMap<String, Object>();
			// 取出配置中所有key
			Enumeration keysEnumeration = propsProperties.keys();
			// 遍历枚举
			while (keysEnumeration.hasMoreElements()) {
				String keyString = keysEnumeration.nextElement().toString();
				// 根据key获取value
				String beanPathString = propsProperties.getProperty(keyString);
				// 实例化
				Object beanObject = Class.forName(beanPathString).newInstance();
				// 存入容器
				propsMap.put(keyString, beanObject);
			}
		} catch (Exception e) {
			// TODO: handle exception
			throw new ExceptionInInitializerError("初始化实例错误");
		}
	}

	/**
	 * 根据Bean 名称获取类
	 * 
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		Object beanObject = null;
		try {
			String beanPathString = propsProperties.getProperty(beanName);
			beanObject = Class.forName(beanPathString).newInstance();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return beanObject;
	}

	public static Object getBeanSingle(String beanName) {

		return propsMap.get(beanName);
	}
}
